package net.huashitong.user.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.util.SysUserUtils;
import net.huashitong.Indicators.dataBean.IndexDataDTO;
import net.huashitong.Indicators.entity.IndexData;
import net.huashitong.Indicators.entity.OneIndex;
import net.huashitong.Indicators.entity.UserInfo;
import net.huashitong.Indicators.filter.OneIndexFilter;
import net.huashitong.Indicators.service.IndexDataService;
import net.huashitong.Indicators.service.UserInfoService;
import net.huashitong.Indicators.utils.DateForIndUtils;
import net.huashitong.Indicators.utils.TokenUtil;
import net.huashitong.user.databean.CollectionDatabean;
import net.huashitong.user.entity.Collection;
import net.huashitong.user.filter.CollectionFilter;
import net.huashitong.user.service.CollectionService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;

import static net.huashitong.Indicators.utils.DataFormateUntil.dataFormat;
import static net.huashitong.Indicators.utils.DataFormateUntil.kexuejishu;

/**
 * 收藏
 *
 * @author lzr
 */
@Controller
@RequestMapping("/app/collection")
public class CollectionController extends JsonBaseController {

    @Autowired
    private CollectionService collectionService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private IndexDataService indexDataService;

    @Override
    protected String getView(String arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 收藏功能
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping("/saveCollection")
    public Message saveCollection(@RequestBody CollectionFilter filter) {
        if (StringUtils.isNotBlank(filter.getAlertId()) && StringUtils.isNotBlank(filter.getUserId())) {
            Collection collection = collectionService.getByUserIdAndAlertId(filter);
            if (ObjectUtils.isNotBlank(collection)) {
                collectionService.delete(collection);
                return coverMessage("200", "取消收藏");
            }
        }
        Collection collection = new Collection();
        collection.setAlertId(filter.getAlertId());
        collection.setPhotoId(filter.getPhotoId());
        collection.setUserId(filter.getUserId());
        collection.setText(filter.getText());
        collection.setCollectionTime(filter.getDate());
        collectionService.save(collection);
        return coverMessage("200", "收藏成功");
    }

    /**
     * 查询收藏
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryCollection")
    public Message queryCollection(@RequestBody CollectionFilter filter) {
        List<Collection> collections = collectionService.queryByUserId(filter);
        List<CollectionDatabean> databeans = new ArrayList<CollectionDatabean>();
        for (Collection collection : collections) {
            CollectionDatabean databean = new CollectionDatabean();
            databean.setAlertId(collection.getAlertId());
            databean.setDate(collection.getCollectionTime());
            databean.setPhotoId(collection.getPhotoId());
            databean.setText(collection.getText());
            databeans.add(databean);
        }
        return coverMessage("200", "获取成功", databeans);
    }

    /**
     * 保存收藏--hyp
     *
     * @param filter openId、codeId、codeType、areaCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/saveCollection", method = RequestMethod.POST)
    public Message saveUserCollection(@RequestBody CollectionFilter filter) {
        //获取当前时间
        String currentTime = new DateForIndUtils().getCurDate("yyyyMMdd HH:mm:ss");
        UserInfo userInfo = userInfoService.getById(filter.getOpenId());
        if (userInfo == null) {
            return coverMessage("501", "openId出错");
        }
        //通过openId验证localToken是否过期(true:未过期，false：过期)
        boolean flag = new TokenUtil().validateToken(userInfo);
        if (!flag) {
            return coverMessage("501", "本地Token过期");
        } else {
            userInfo.setLocalTokenTime(currentTime);
            userInfoService.update(userInfo);
        }

        Collection collection = new Collection();
        collection.setDateTime(filter.getDatetime());    //指标时间
        collection.setCodeId(filter.getCodeId());        //指标编码
        collection.setCodeType(filter.getCodeType());    //指标类型，Y月度 J季度，N年度
        collection.setAreaCode(filter.getAreaCode());    //地区编码
        collection.setAreaType(filter.getAreaType());    //A B C D   市级 区级  十五个 全国
        collection.setCollectionTime(currentTime);        //添加收藏的时间
        collection.setUserId(filter.getOpenId());        //openId
        collectionService.save(collection);
        return coverMessage("200", "收藏成功");
    }

    /**
     * 删除收藏---hyp
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/deleteCollection", method = RequestMethod.POST)
    public Message deleteUserCollection(@RequestBody CollectionFilter filter) {
        UserInfo userInfo = userInfoService.getById(filter.getOpenId());
        if (userInfo == null) {
            return coverMessage("501", "openId出错");
        }
        //通过openId验证localToken是否过期(true:未过期，false：过期)
        boolean flag = new TokenUtil().validateToken(userInfo);
        if (!flag) {
            return coverMessage("501", "本地Token过期");
        } else {
            //更新本地token时间
            String currentTime = new DateForIndUtils().getCurDate("yyyyMMdd HH:mm:ss");
            userInfo.setLocalTokenTime(currentTime);
            userInfoService.update(userInfo);
        }
        collectionService.deleteById(filter.getSysId());
        return coverMessage("200", "取消成功");
    }

    /**
     * 查询收藏---hyp
     *
     * @param filter openId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/query", method = RequestMethod.POST)
    public Message queryUserConllection(@RequestBody CollectionFilter filter) {
        UserInfo userInfo = userInfoService.getById(filter.getOpenId());
	/*	if(userInfo==null){
			return coverMessage("501","openId出错");
		}
		//通过openId验证localToken是否过期(true:未过期，false：过期)
		boolean flag = new TokenUtil().validateToken(userInfo);
		if(!flag){
			return coverMessage("501","本地Token过期");
		}else{
			//更新本地token时间
			String currentTime = new DateForIndUtils().getCurDate("yyyyMMdd HH:mm:ss");
			userInfo.setLocalTokenTime(currentTime);
			userInfoService.update(userInfo);
		}
*/
        filter.setUserId(filter.getOpenId());
        List<Collection> list = collectionService.query(filter);
        List<Map<String, Object>> resList = new ArrayList<>();
        for (Collection c : list) {
            Map<String, Object> map = new HashMap<>();
//			String codeID, String areaCode,String codeType
            List<IndexDataDTO> dataList = indexDataService.queryListIndexDate(c.getCodeId(), c.getDateTime(), c.getAreaCode(), c.getCodeType(), filter.getAreaType());
            if (dataList.size()>0) {
                map.put("sysId", c.getSysId());
                map.put("openId", c.getUserId());
                map.put("collectionTime", c.getCollectionTime());
                map.put("codeId", c.getCodeId());
                //map.put("codeName",dataList.get(0).getCodeName());
                map.put("codeType", c.getCodeType());
                map.put("areaCode", c.getAreaCode());
                //map.put("areaName",dataList.get(0),)
                map.put("currentValue", dataFormat(kexuejishu(dataList.get(0).getCurrentValue())));
                map.put("codeName", dataList.get(0).getCodeName());
                map.put("cumulativeValue", dataFormat(kexuejishu(dataList.get(0).getCumulativeValue())));
                map.put("ratio", dataFormat(kexuejishu(dataList.get(0).getCumulativeRatio())));
                map.put("areaName", dataList.get(0).getAreaName().replace("市", ""));
                map.put("datetime", dataList.get(0).getDatetime());
                map.put("areaType", dataList.get(0).getAreaType());
                map.put("unit", dataList.get(0).getUnit());
                resList.add(map);
            }
        }

        return coverMessage("200", "获取成功", resList);
    }

    @ResponseBody
    @RequestMapping(value = "/searchInfo", method = RequestMethod.POST)
    public Message searchInfo(@RequestBody CollectionFilter filter) {

        if (StringUtils.isBlank(filter.getKeyWord()))
            return coverMessage("500", "无搜索关键字");

        List<IndexDataDTO> dtos = collectionService.getCollects(filter.getKeyWord(), filter.getOpenId());
        List<Map<String, Object>> listmap = new ArrayList<>();
        for (IndexDataDTO item : dtos) {
            Map<String, Object> map = new HashMap<>();
            map.put("codeId", StringUtils.isBlank(item.getCodeId()) ? "-" : item.getCodeId());
            map.put("codeName", StringUtils.isBlank(item.getCodeName()) ? "-" : item.getCodeName());
            map.put("currentValue", StringUtils.isBlank(item.getCurrentValue()) ? "-" : item.getCurrentValue());
            map.put("cumulative", StringUtils.isBlank(item.getCumulativeValue()) ? "-" : item.getCumulativeValue());
            map.put("ratio", StringUtils.isBlank(item.getCumulativeRatio()) ? "-" : item.getCumulativeRatio());
            map.put("areaCode", StringUtils.isBlank(item.getAreaCode()) ? "-" : item.getAreaCode());
            map.put("areaName", StringUtils.isBlank(item.getAreaName()) ? "-" : item.getAreaName());
            map.put("unit", StringUtils.isBlank(item.getUnit()) ? "-" : item.getUnit());
            map.put("areaType", StringUtils.isBlank(item.getAreaType()) ? "-" : item.getAreaType());
            map.put("sysId", StringUtils.isBlank(item.getSysId()) ? "-" : item.getSysId());
            map.put("codeType", StringUtils.isBlank(item.getCodeType()) ? "-" : item.getCodeType());

            listmap.add(map);
        }

        return coverMessage("200", "successful", listmap);
    }


}
